<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class authen extends CI_Controller {

	public function index()
	{	
		$all_session = $this->session->all_userdata();

		if(@$all_session['login'] == 0)
		{
			$this->load->view('login');
		} else {
			redirect();
		}
	}

	public function login()
	{
		
		$input = array(
			'mem_name' => $this->input->post('mem_name'),
			'mem_pass' => md5($this->input->post('mem_pass'))
		);

		if($input['mem_name'] != null && $input['mem_pass'] != null)
		{
			$session['login'] = $this->authen_model->checklogin($input);
			$this->session->set_userdata($session);
				
			$seg1 = $this->uri->segment(1);
			$url = base_url().'index.php/'.$seg1;

			if($session['login'][0]['mem_type'] == 3)
			{
				$this->session->sess_destroy();
				redirect('authen/index/error');
			}

			if($session['login'] == 0){

				$check_type = $this->authen_model->check_type($input);
				if($check_type != null){

					$log_file = array(						
						'log_url' => $url,
						'log_action' => 'Login',
						'log_status' => 'Fail',
						'mem_id' => $check_type[0]['mem_id'],
						'log_ip' => $_SERVER['REMOTE_ADDR']						
					);

					$this->logfile_model->add_logfile($log_file);
				}

				$this->session->sess_destroy();
				redirect('authen/index/error');

			}else{

				if($session['login'][0]['mem_type'] == 2 || $session['login'][0]['mem_type'] == 1) {

					$log_file = array(						
						'log_url' => $url,
						'log_action' => 'Login',
						'log_status' => 'Pass',
						'mem_id' => $session['login'][0]['mem_id'],
						'log_ip' => $_SERVER['REMOTE_ADDR']						
					);

					$this->logfile_model->add_logfile($log_file);

				}

				$mem_id = $session['login'][0]['mem_id'];
				$mem_type = $session['login'][0]['mem_type'];

				if($mem_type == 2 || $mem_type == 1)
				{
					$check_grant = $this->authen_model->check_grant($mem_id);

					date_default_timezone_set("Asia/Bangkok");
					$now = date("Y-m-d H:i");

					$exp = (strtotime($check_grant[0]['grant_end']) - strtotime($now))/  ( 60 * 60 );

					if($check_grant[0]['grant_end'] != NULL)
					{
						if($exp < 0) {

							$reset_grant = array(
								'mem_id' => $mem_id,
								'mem_type' => 0
							);
							$this->authen_model->reset_grant($reset_grant);

							$session['login'] = $this->authen_model->checklogin($reset_grant);
							$this->session->set_userdata($session);
							
						}
					}					

				}
				

				redirect();

			}
		}
	
	}

	public function logout()
	{
		$this->session->sess_destroy();
		redirect('authen');
	}

}